<?php

namespace app\controllers\admin;

use Yii;
use app\models\Material;
use app\models\search\Material as MaterialSearch;
use app\controllers\admin\BaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * MaterialController implements the CRUD actions for Material model.
 */
class MaterialController extends BaseController {
    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Material models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new MaterialSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Material model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function actionImport() {
        if (!Yii::$app->request->isPost) {
            return $this->render('import', []);
        }
        $text = Yii::$app->request->post('text');
        $this->transaction(function() use ($text) {
            Yii::$app->db->createCommand('
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
TRUNCATE `material`;
TRUNCATE `user_material`;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
            ')->execute();

            foreach (explode("\n", $text) as $line) {
                $line = trim($line);
                if(empty($line)) continue;

                $model = new Material();
                list($model->name,
                $model->attribute,
                $model->country_id,
                $model->inventory,
                $model->unit,
                $model->price,
                $model->level,
                $model->description) = explode(',', $line);
                $model->name = trim($model->name);
                $model->attribute = trim($model->attribute);
                $model->country_id = trim($model->country_id);
                $model->inventory = trim($model->inventory);
                $model->unit = trim($model->unit);
                $model->price = trim($model->price);
                $model->level = trim($model->level);
                $model->description = trim($model->description);
                $model->save();
            }
        });
        return $this->redirect(['index',]);
    }

    /**
     * Creates a new Material model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new Material();

        if ($model->load(Yii::$app->request->post()) && $model->save(true, null, false)) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Material model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Material model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id) {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Material model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Material the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = Material::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('页面不存在');
        }
    }
}
